import { useEffect, useRef, useState } from 'react'

export default function useCountDown (initCount = 10, callBack = () => {}) {
//   const timeId = useRef<{id:number}>({ id: 0 })
  const timeId = useRef<number>(0)
  const [count, setCount] = useState(initCount)

  const start = () => {
    setCount(initCount)
    timeId.current = window.setInterval(() => {
      setCount((count) => count - 1)
    }, 1000)
  }
  useEffect(() => {
    return () => {
      // console.log('..........')
      clearInterval(timeId.current)
    }
  }, [])

  useEffect(
    () => {
      // console.log(count, timeId.current)
      if (count === 0) {
        clearInterval(timeId.current)
        callBack()
      }
    },
    [count, callBack]
  )

  return { count, start }
}
